package com.jml.juc.BlockingQueue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class MyConditionLock {
    private int number = 0;
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    /**
     * ⽣产
     */
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //1. 判断
            while(number != 0){
                //this.wait();
                condition.await();
            }
            //2. ⼲活
            number++;
            System.out.println(Thread.currentThread().getName() +"\t "+number);
            //3.通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
    /**
     * 消费
     */
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //1. 判断
            while(number == 0){
                //this.wait();
                condition.await();
            }
            //2. ⼲活
            number--;
            System.out.println(Thread.currentThread().getName() +"\t "+number);
            //3.通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
/**
 * 题⽬：现在两个线程，可以操作初始值为零的⼀个变量，
 * 实现⼀个线程对该变量加1，⼀个线程对该变量-1，
 * 实现交替，来10轮，变量初始值为0.
 * 1.⾼内聚低耦合前提下，线程操作资源类
 * 2.判断/⼲活/通知
 * 3.防⽌虚假唤醒(判断只能⽤while，不能⽤if)
 * 知识⼩总结：多线程编程套路+while判断+新版写法
 */
public class ProdConsumerLockDemo {
    public static void main(String[] args) {
        MyConditionLock myCondition = new MyConditionLock();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.increment();
                } catch ( Exception e) {
                    e.printStackTrace();
                }
            }
        }, "师傅A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "师傅B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "顾客A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "顾客B").start();
    }
}
